package com.bigfreakindeals.Protocols.SoapHandlers;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class FacebookSignupHandler {
	
	static final String STATUS = "status";
	static final String ERROR = "error";

	static boolean isSignUp;

	String feedUrl;

	private static final String SOAP_ACTION = "1";
	private static final String METHOD_NAME = "bigfreakindeals";
	private static final String NAMESPACE = "1";

	Context context;
	
	public FacebookSignupHandler(String feedUrl, Context context) {
		// TODO Auto-generated constructor stub
		this.feedUrl = feedUrl;
		this.context = context;
		parse();
	}
	
	public void parse() {

		try {

			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			System.out.println(feedUrl);
			System.out.println("signup with facebook handler starts..."+envelope);
			
			HttpTransportSE androidHttpTransport = new HttpTransportSE(feedUrl);

			try {
				androidHttpTransport.call(SOAP_ACTION, envelope);
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}

			SoapObject response = (SoapObject) envelope.getResponse();

					String signup = response.getProperty(STATUS).toString();
			if (signup != null && signup.length() > 0) {
				if (signup.contentEquals("false")) {
					isSignUp = false;
				} else {
					isSignUp = true;
				}
			}
			if (isSignUp) {
				Intent intent = new Intent(Constant.EVENTS_FACEBOOKSIGNUPSUCCESS);

				ApplicationEx.getInstance().sendBroadcast(intent);

				return;
			}else{
				String error = response.getProperty(ERROR).toString();
				Intent intent = new Intent(Constant.EVENTS_FACEBOOK_LOGINERROR);
				intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, error);
				ApplicationEx.getInstance().sendBroadcast(intent);
				return;
			}
			
		}catch (IOException e1) {
			// TODO Auto-generated catch block

			Intent intent = new Intent(Constant.EVENTS_SIGNUPERROR);
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);

		} catch (Exception e1) {

			Intent intent = new Intent(Constant.EVENTS_FACEBOOKSIGNUPERROR);
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
		}

	}

}
